import * as React from 'react';
import { createElement } from 'react';
import classNames from 'classnames';
import { generatorClass } from '../../utils';
import './base.less';
import { FiledMask } from './field-mask';
import { Form, message } from 'antd';

function isValidRegex(str) {
  try {
    new RegExp(str); // 尝试创建正则对象
    return true; // 没有错误，说明是有效正则
  } catch (e) {
    return false; // 捕获错误，说明不是有效正则
  }
}

export const BaseWrapper: React.FC<any> = function BaseWrapper({
  title,
  isRequired,
  isRepeat,
  columnConfig,
  children,
  hasFormItem = true,
  pattern,
  cols,
  patternMessage,
  ...otherProps
}) {
  const { format, description, status } = (columnConfig || {}) as any;
  const rootClassNames = classNames(generatorClass('field-base'));

  const engineProps = otherProps as any;

  const renderChildren = () => {
    const name = engineProps?.componentId || engineProps?.__id;

    if (!hasFormItem) {
      return children;
    }

    const rules = [{ required: isRequired, message: `${title}不能为空！` }];
    // 匹配单行文本、多行文本输入框校验
    if (
      children &&
      children.props &&
      children.props.componentName &&
      ['FieldInput', 'FieldTextarea'].includes(children.props.componentName)
    ) {
      // 默认正则规则
      const ruleMap = {
        2: {
          value: /^1[3-9]\d{9}$/,
          message: '手机号格式错误',
        },
        3: {
          value: /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/,
          message: '邮箱格式错误',
        },
        4: {
          value: /^\d{15}$|^\d{17}[\dXx]$/,
          message: '身份证号格式错误',
        },
        5: {
          value: /^[\u4e00-\u9fa5]+$/,
          message: '中文格式错误',
        },
        6: {
          value: /^[a-zA-Z]+$/,
          message: '英文格式错误',
        },
      };
      // 排除默认选项
      if (format !== 1) {
        rules[1] = {
          pattern: ruleMap[format].value,
          message: ruleMap[format].message,
        };
      }
      // 用户填写了正则，覆盖上方
      if (pattern && isValidRegex(pattern)) {
        rules[1] = {
          pattern: new RegExp(pattern),
          message: patternMessage || '格式错误',
        };
      }
    }
    // 编写else if 匹配其他物料 然后写对应正则

    // 是否允许重复值
    if (isRepeat) {
      // 异步校验函数
      const validateUsername = async (rule: any, value: string) => {
        if (!value) {
          return Promise.reject('用户名不能为空');
        }
        try {
          // 发送请求到后端检查用户名是否存在 测试地址
          // const response = await axios.post('/api/check-username', { username: value });
          const response = {
            data: {
              exists: true,
            },
          };
          if (response.data.exists) {
            return Promise.reject('该用户名已被注册');
          }
        } catch (error) {
          message.error('网络错误，请稍后再试');
          return Promise.reject('检查用户名时出错');
        }
        return Promise.resolve();
      };
      // 暂未开发，需配合后端接口查询重名
      // rules.push({ validator: validateUsername });
    }
    return (
      <Form.Item label="" name={name} rules={rules}>
        {children}
      </Form.Item>
    );
  };

  return (
    <div className={rootClassNames} style={{ width: `calc(${(cols / 24) * 100 + '%'} - 6px)` }}>
      {/* <ChangePosition /> */}
      <FiledMask {...otherProps} />
      <div className={generatorClass('field-base-title')}>
        {isRequired && (
          <span
            style={{
              marginRight: '4px',
              color: '#ff4d4f',
              fontSize: '14px',
              fontFamily: 'SimSun, sans-serif',
              lineHeight: 1,
            }}
            className="isRequired"
          >
            *
          </span>
        )}
        {title}
      </div>
      <div className={generatorClass('field-base-content')}>
        {status === '3' ? <div>--</div> : renderChildren()}
      </div>
      <div className={generatorClass('field-base-desc')}>{description}</div>
    </div>
  );
};
